#include "glemfwidget.h"

GlEmfWidget::GlEmfWidget()
{
    _isSelectorVisible = false;
}

void GlEmfWidget::mouseReleaseEvent(QMouseEvent *event)
{
    _lastPos = event->pos();
    _isSelectorVisible = true;
    _sendEmfInfoAndFillIntersectionPoints();
    updateGL();
}

void GlEmfWidget::paintGL()
{
    GLWidget::paintGL();

    _grid.draw(this);
    if(_isSelectorVisible)
    {        
        _selector.draw(_projectWindowCoordinates(_lastPos), _emfPoints);
    }

    for(int i=0; i<_drawables.size(); i++)
    {
        _drawables[i]->draw(_currentCoordsTransformer);
    }
}

void GlEmfWidget::_applyScaleAndTranslate()
{
    GLWidget::_applyScaleAndTranslate();

    QRectF newViewport;
    double w = width()*100.0/_scale;
    double h = height()*100.0/_scale;
    newViewport.setCoords(-_translateX - w/2, -_translateY - h/2, -_translateX + w/2, -_translateY + h/2);
    _selector.setViewPort(newViewport);
}

void GlEmfWidget::_sendEmfInfoAndFillIntersectionPoints()
{
    _emfPoints.clear();
    QSharedPointer<QMap<int, QPointF> > emfInfo = QSharedPointer<QMap<int, QPointF> >(new QMap<int, QPointF>());
    for(int i = 0; i < _drawables.size(); i++)
    {
        EmfDrawable *emfDrawable = dynamic_cast<EmfDrawable*>(_drawables.value(i));
        QPointF lastPos = _projectWindowCoordinates(_lastPos);
        double xCoord = _grid.getXCoordFromPoint(lastPos.x());
        double yCoord = emfDrawable->getValueByTime(xCoord);
        emfInfo->insert(emfDrawable->getTag(),
                        QPointF(xCoord, yCoord));

        _emfPoints.push_back(QPointF(lastPos.x(), _currentCoordsTransformer->transform(QPointF(xCoord, yCoord)).y()));
    }
    emit sendEmfInfo(emfInfo);
}

